package com.example.shushiyunsst.fragment.main.wallet.sub

import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import com.alibaba.fastjson.JSON
import com.example.library_common.base.BaseLazyDataBindingFragment
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.even.MessageWrap
import com.example.library_common.utils.even.TO_REFRESH_BALANCE_INFO
import com.example.shushiyunsst.R
import com.example.shushiyunsst.databinding.ExchangePassTransferFragmentBinding
import com.example.shushiyunsst.fragment.getUserBalanceInfo
import com.example.shushiyunsst.fragment.main.wallet.bean.WalletHeadBean
import com.example.shushiyunsst.scan.ScanFrameFragment
import com.example.shushiyunsst.scan.ScanResListener
import com.example.shushiyunsst.util.PayingPassWordVerifyPop
import com.example.wallet.bean.BalanceInfoBean
import com.example.wallet.db.BalanceInfoManager
import com.example.wallet.db.UserInfoManager
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.interfaces.SimpleCallback
import com.senon.modularapp.util.JssSpannableString

/**
 * 交易积分转账
 * */
class ExchangePassTransferFragment : BaseLazyDataBindingFragment<ExchangePassTransferFragmentBinding>(),
    View.OnClickListener {

    companion object {
        fun newInstance(item: BalanceInfoBean.ListBean): ExchangePassTransferFragment {
            val args = Bundle()
            args.putSerializable("item", item)
            val fragment = ExchangePassTransferFragment()
            fragment.arguments = args
            return fragment
        }
    }

    private var item: BalanceInfoBean.ListBean? = null

    override fun layoutId(): Int {
        return R.layout.exchange_pass_transfer_fragment
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        item = arguments?.getSerializable("item") as BalanceInfoBean.ListBean
    }

    override fun lazyInit() {
        val walletHeadBean = WalletHeadBean(item?.balance, item?.balanceCny,item?.tokenType)
        loadRootFragment(R.id.wallet_header, WalletHeadFragment.newInstance(walletHeadBean))

        val balanceInfoBean = BalanceInfoManager.mBalanceInfoManager.getBalanceInfoBean()
        if (balanceInfoBean == null) {
            getUserBalanceInfo(_mActivity)
            return
        }
        presentBalanceInfo(balanceInfoBean)
    }

    override fun initView(view: View) {

        val mToolbar: Toolbar = view.findViewById(R.id.mToolbar)
        mToolbar.setNavigationOnClickListener { onBackPressedSupport() }

        viewBinder.item = item
        viewBinder.onViewClick = this
    }

    override fun handMessage(msg: MessageWrap?) {

        if (msg?.message == TO_REFRESH_BALANCE_INFO) {
            val balanceInfoBean = BalanceInfoManager.mBalanceInfoManager.getBalanceInfoBean()
            presentBalanceInfo(balanceInfoBean)
        }
    }

    private fun presentBalanceInfo(balanceInfoBean: BalanceInfoBean?) {

        val feeBeanBean = BalanceInfoManager.mBalanceInfoManager.getFeeBeanBean()
        val minerFees = feeBeanBean?.sst

        val availableValue = String.format("%.4f", balanceInfoBean?.balanceInfo?.integralBalance)

        val moneyType = item?.tokenType

        val span = JssSpannableString(
            _mActivity,
            "可用${availableValue}$moneyType ,矿工费: $minerFees$moneyType"
        )
            .first(availableValue).textColor(R.color.PrimaryColor)
            .first(minerFees.toString()).textColor(R.color.PrimaryColor)


        viewBinder.feedingTv.text = span
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.mSaner -> {
                val newInstance = ScanFrameFragment.newInstance()
                newInstance.setScanResListener(object : ScanResListener {
                    override fun onResStr(resStr: String) {
                        viewBinder.addressTv.setText(resStr)
                    }
                })
                start(newInstance)
            }
            R.id.forAll -> {
                val balanceInfoBean = BalanceInfoManager.mBalanceInfoManager.getBalanceInfoBean()
                val availableCount = balanceInfoBean?.balanceInfo?.integralBalance
                viewBinder.availableCount.setText(availableCount.toString())
            }
            R.id.sureTv -> {
                if (!checkInfo()) {
                    return
                }
                val mPop = PayingPassWordVerifyPop(_mActivity)
                XPopup.Builder(_mActivity)
                    .setPopupCallback(object : SimpleCallback() {
                        override fun onDismiss(popupView: BasePopupView?) {
                            super.onDismiss(popupView)
                            if (mPop.getIsOnVerifyPop()) {
                                if (mPop.getVerifyPop()) {
                                    sendAll()
                                } else {
                                    Toast.makeText(_mActivity, "支付密码错误", Toast.LENGTH_SHORT).show()
                                }
                            }
                        }
                    })
                    .asCustom(mPop)
                    .show()
            }
        }
    }

    private fun sendAll() {
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val toAddr = viewBinder.addressTv.text.toString()
        val txNums = viewBinder.availableCount.text.toString()
        val map = mapOf(
            "fromAddr" to userInfo?.sysWalletAddress,
            "toAddr" to toAddr,
            "txNums" to txNums
        )
        RestClient.builder()
            .url(R.string.transferI)
            .raw(JSON.toJSONString(map))
            .success {
                Toast.makeText(_mActivity, "转账成功", Toast.LENGTH_SHORT).show()
                getUserBalanceInfo(_mActivity)
                onBackPressedSupport()
            }
            .failure {
                Toast.makeText(_mActivity, "转账失败", Toast.LENGTH_SHORT).show()
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
            }.build().post()
    }

    private fun checkInfo(): Boolean {
        var flag = true
        val toAddr = viewBinder.addressTv.text.toString()
        val txNums = viewBinder.availableCount.text.toString()
        if (toAddr.isNullOrBlank()) {
            Toast.makeText(_mActivity, "请输入转账地址", Toast.LENGTH_SHORT).show()
            flag = false
        }

        if (txNums.isNullOrBlank()) {
            Toast.makeText(_mActivity, "请输入转账地址数量", Toast.LENGTH_SHORT).show()
            flag = false
        }

        return flag
    }


}